import React from 'react'
import {connect} from 'react-redux'
import { Form, Select, Input, Row, Col, InputNumber, Spin, message, Button, Alert } from "antd";
import "styles/loan-billing/repayment-content.scss"
import {messages,queryCurrencyPrecision} from "share/common";
import ImageUpload from 'components/image-upload';
import Inputter from 'components/inputter';
import borrowService from 'containers/loan-billing/borrow-and-return.service';
import baseService from 'share/base.service'
const FormItem = Form.Item;
const TextArea = Input.TextArea;
const Option = Select.Option;
const formItemLayout = {
  labelCol: { span: 6 },
  wrapperCol: { span: 14, offset: 1 }
};

class RepaymentContent extends React.Component{
  constructor(props){
    super(props);
    this.state = {
      info: {},
      paymentType: 'cash',
      repayAttachment: [],
      repayAttachmentImages: [],
      selectLoading: false,
      accountOptions: [], //收款人开户名option
      acceptAccount: '', //收款人开户账号
      acceptBankName: '', //收款人银行名称
      bankSpin: false,
      companyBankOption: [],
      copyData: [], //新租户下更换支付方式还原companyBankOption
      loading: false,
      loanRefund: false,
      printLoading: false,
      paymentOption: []
    }
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.repayFrame === this.props.repayFrame)
      return;
    if(!nextProps.repayFrame){
      this.props.form.resetFields();
      this.setState({
        info: {},
        repayAttachment: [],
        repayAttachmentImages: [],
        loanRefund: false
      });
      return !1;
    }
    this.props.form.resetFields();
    const { isOldCompany } = this.props;
    this.setState({
      info: nextProps.info,
      loanRefund: nextProps.loanRefund
    },() => {
      let { info } = this.state;
      borrowService.getLineDetail(info.id,true).then(res => {
        info = Object.assign(res.data,info);
        this.setState({ info }, () => {
          Promise.all([
            baseService.getFinanceConfig({ companyId: info.companyId, itemGroupCode: 'REPAYMENT_1_G1', formOID: info.formOid }),
            borrowService.getCompanyBank({ page: 0, size: 100, companyOID: info.companyOID })
          ]).then(response => {
            let type = '';
            if (info.loanTypeName === '公务卡转因私') {
              type = 'cash'
            } else {
              type = 'card'
            }
            this.setState({
              paymentType: type,
              paymentOption: response[0].data,
              companyBankOption: response[1].data,
              copyData: response[1].data
            });
          });
          if (isOldCompany) {
            this.getLegalList();
          } else {
            this.getCompany();
          }
        });
      }).catch(() => {
        message.error(messages('loan-billing.key25')/*系统异常*/);
      })
    })
  };

  getFinanceConfig = () => {
    console.log(this.props.info);
    // baseService.getFinanceConfig();
  };

  //获取老租户法人实体
  getLegalList = () => {
    this.setState({selectLoading: true});
    borrowService.getLegalList({page: 0, size: 150}).then(res => {
      this.setState({
        selectLoading: false,
        accountOptions: res.data,
        acceptAccount: res.data[0].cardNumber,
        acceptBankName: res.data[0].accountBank
      })
    }).catch(e => {
      this.setState({selectLoading: false});
      message.error(e.response.data.message);
    })
  };

  //获取新租户公司
  getCompany = () => {
    this.setState({selectLoading: true});
    const { info } = this.state;
    borrowService.getCompany({page: 0, size: 100, setOfBooksId: info.setOfBooksId}).then(res => {
      let temp = [];
      res.data.map(item => {
        temp.push({
          id:item.companyOID,
          companyName: item.name
        });
      });
      this.setState({
        selectLoading: false,
        accountOptions: temp,
        acceptAccount: '',
        acceptBankName: '',
      });
    }).catch(e => {
      this.setState({selectLoading: false});
      message(e.response.data.message);
    })
  };

  //还款方式修改
  handlePaymentTypeChange = (value) => {
    this.setState({paymentType: value},() => {
      const { isOldCompany } = this.props;
      const { accountOptions, copyData } = this.state;
      let tempRes = JSON.parse(JSON.stringify(copyData));
      this.setState({companyBankOption: tempRes});
      let temp = {
        acceptAccount: isOldCompany ? accountOptions[0].cardNumber : undefined,
        acceptBankName: isOldCompany ? accountOptions[0].accountBank : undefined
      };
      value === 'cash' && (temp.remark = '');
      this.props.form.setFieldsValue(temp);
    });
  };

  //获取上传图片的OId
  getUploadImageOId = (values) => {
    let repayAttachment = [];
    values.map(item => {
      repayAttachment.push({attachmentOID: item.attachmentOID})
    });
    this.setState({ repayAttachment, repayAttachmentImages: values })
  };

  //老租户修改开户名
  oldChangeAccount = (value) => {
    this.state.accountOptions.map(item => {
      if(item.id === value) {
        this.setState({
          acceptAccount: item.cardNumber,
          acceptBankName: item.accountBank
        }, () => {
          this.props.form.setFieldsValue({
            acceptAccount: this.state.acceptAccount,
            acceptBankName: this.state.acceptBankName
          })
        })
      }
    })
  };

  //新租户修改开户名
  newChangeAccount = (value) => {
    this.setState({
      bankSpin : true,
      acceptAccount: '',
      acceptBankName: ''
    },() => {
      this.props.form.setFieldsValue({
        acceptAccount: this.state.acceptAccount,
        acceptBankName: this.state.acceptBankName
      })
    });
    borrowService.getCompanyBank({page: 0, size: 100, companyOID: value}).then(res => {
      this.setState({
        bankSpin: false,
        companyBankOption: res.data
      })
    }).catch(() => {
      this.setState({
        bankSpin: false,
        companyBankOption: []
      });
    })
  };

  //修改新租户的开户账号
  handleChangeAcceptAccount = (value) => {
    const { companyBankOption } = this.state;
    companyBankOption.map(item => {
      if(item.bankAccountNumber === value){
        this.setState({
          acceptBankName: item.bankBranchName,
          acceptAccount: item.bankAccountNumber
        },() => {
          this.props.form.setFieldsValue({
            acceptAccount: this.state.acceptAccount,
            acceptBankName: this.state.acceptBankName
          })
        })
      }
    })
  };

  handleSave = (isNeedPrint = false) => {
    this.props.form.validateFieldsAndScroll((err, values) => {
      if(!err) {
        const { info, repayAttachment, paymentType, loanRefund, accountOptions } = this.state;
        values.loanBillOid = info.loanBillOid;
        values.loanApplicationOid = info.loanBillOid;
        values.repayAttchment = repayAttachment;
        values.loanLineId = info.id;
        values.transactionDetailId = info.transactionDetailId;
        loanRefund && (values.isFinance = true);
        if (values.paymentType === 'card') {
          if (values.acceptAccountName) {
            values.acceptAccountName = accountOptions.filter(item => item.id === values.acceptAccountName)[0].companyName;
          }
        }
        this.setState({ loading: true, printLoading: true });
        let method = paymentType === 'cash' ? 'cashRepayment' : 'cardRepayment';
        isNeedPrint && (method = 'saveAndPrintRepayment');
        // console.log('values', values)
        if (values.paymentType === '转永久还款') {
          delete values.paymentType
        }
        borrowService[method](values).then(res => {
          this.setState({ loading: false, printLoading: false });
          message.success(messages('common.operate.success'));
          this.props.close(true);
          isNeedPrint && window.open(res.data.link, '_blank');
        }).catch(e => {
          this.setState({ loading: false, printLoading: false });
          message.error(`${messages('common.operate.filed')}，${e.response.data.message}`)
        })
      }
    })
  };

  handleChangeBankNo = (value) => {
    const { info } = this.state;
    let account = info.payeeType === 1002 ? value.result[0].bankAccountName : value.result[0].venBankNumberName;
    let name = info.payeeType === 1002 ? value.result[0].branchName : value.result[0].bankName;
    this.props.form.setFieldsValue({
      payAccountName: account,
      payBankName: name
    })
  };

  render(){
    const { info, paymentType, repayAttachmentImages, selectLoading, accountOptions, acceptAccount,
      acceptBankName, bankSpin, companyBankOption, loading, loanRefund, printLoading, paymentOption } = this.state;
    const { getFieldDecorator } = this.props.form;
    let showData = false;
    return(
      <div className='new-repayment-frame'>
        {
          !loanRefund && <Alert type='warning' showIcon message={messages('loan-billing.key154')/*还款单提交后，还需财务复核方可生效*/}/>
        }
        <Form>
          <div className='title'>{messages('loan-billing.key72')/*还款方信息*/}</div>
          <FormItem {...formItemLayout} label={messages('loan-billing.key73')/*借款行*/}>
            {getFieldDecorator('loanLineNumber', {
              rules: [{
                required: true,
                message: messages('common.please.select')
              }],
              initialValue: info.sequence
            })(
              <Input disabled/>
            )}
          </FormItem>
          <FormItem {...formItemLayout} label={messages('finance-1.key337')/*还款人*/}>
            {getFieldDecorator('payee',{
              initialValue: info.payeeName
            })(
              <Input disabled={true}/>
            )}
          </FormItem>
          <FormItem {...formItemLayout} label={messages('loan-billing.key104')/*支付流水号*/}>
            {getFieldDecorator('transactionDetailCode',{
              initialValue: info.transactionDetailCode
            })(
              <Input disabled/>
            )}
          </FormItem>
          <Row>
            <Col span={6} className="form-define-title required">{messages('loan-billing.key7')/*还款金额*/}：</Col>
            <Col span={3} offset={1}><FormItem>{getFieldDecorator('curreny', {
              initialValue: info.currencyCode
            })(<Input disabled/>)}</FormItem></Col>
            <Col span={5}>
              <FormItem>
                {getFieldDecorator('repaymentValue', {
                  rules: [{
                    required: true,
                    message: messages('common.please.enter')
                  }, {
                    pattern: /[1-9]/,
                    message: messages('loan-billing.key74')/*还款金额要大于0*/
                  }],
                  initialValue: info.stayWriteoffAmount || info.stayWriteOffAmount
                })(
                  <InputNumber 
                    min={0}
                    max={info.stayWriteoffAmount || info.stayWriteOffAmount}
                    precision={queryCurrencyPrecision(info.currencyCode)}
                    className="input-number"
                    disabled={this.props.profile['ca.opt.didi.refund.amount.disabled']}
                    formatter={value => `${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
                    parser={value => value.replace(/\$\s?|(,*)/g, '')}
                  />
                )}
              </FormItem>
            </Col>
          </Row>
          <FormItem {...formItemLayout} label={messages('loan-billing.key3')/*还款方式*/} className={'paymentType-select'}>
            {getFieldDecorator('paymentType', {
              rules: [{
                required: true,
                message: messages('common.please.enter')
              }],
              initialValue: info && info.loanTypeName && info.loanTypeName === '转永久餐厅临时找赎备用金' ? "转永久还款" : info.loanTypeName === '公务卡转因私' ? 'cash' : 'card'
            })(
              info && info.loanTypeName && info.loanTypeName === '转永久餐厅临时找赎备用金' ? <Input disabled  /> : <Select disabled onChange={this.handlePaymentTypeChange} getPopupContainer={() => document.getElementsByClassName('paymentType-select')[0]}>
                {
                  paymentOption.map(item => <Option key={item.itemCode}>{item.showName}</Option>)
                }
              </Select>
            )}
          </FormItem>
          { paymentType === 'card' && showData && (
            <div>
              <FormItem {...formItemLayout} label={messages('loan-billing.key76')/*开户账号*/}>
                {getFieldDecorator('payAccount', {
                  rules: [{
                    required: true,
                    message: messages('common.please.enter')
                  }],
                  initialValue: info.payeeAccountNumber
                })(
                  <Inputter
                    placeholder={messages('common.please.enter')}
                    type={info.payeeType === 1002 ? 'bank_card' : 'vendor_bank'}
                    valueKey={info.payeeType === 1002 ? 'bankAccountNo' : 'bankAccount'}
                    listExtraParams={info.payeeType === 1002 ? { userOID: info.payeeOid } : { vendorInfoId: info.payeeId }}
                    onOk={this.handleChangeBankNo}
                  />
                )}
              </FormItem>
              <FormItem {...formItemLayout} label={messages('loan-billing.key75')/*开户名*/}>
                {getFieldDecorator('payAccountName', {
                  rules: [{
                    required: true,
                    message: messages('common.please.enter'),
                  }],
                  initialValue: info.payeeAccountName
                })(
                  <Input placeholder={messages('common.please.enter')} />
                )}
              </FormItem>
              <FormItem {...formItemLayout} label={messages('loan-billing.key77')/*开户银行*/} className="pay-bank-container">
                {getFieldDecorator('payBankName', {
                  rules: [{
                    required: true,
                    message: messages('common.please.select')
                  }],
                  initialValue: info.payeeBankBranchName
                })(
                  <Input placeholder={messages('common.please.enter')} />
                )}
              </FormItem>
              <FormItem {...formItemLayout} label={messages('loan-billing.key78')/*银行回单号*/}>
                {getFieldDecorator('bankReceiptNumber', {
                  rules: [{
                    max: 50,
                    message: messages('common.max.characters.length', {max: 50})
                  }],
                })(
                  <Input/>
                )}
              </FormItem>
            </div>
          )}
          <FormItem {...formItemLayout} label={messages('common.remark')}>
            {getFieldDecorator('remark', {
              rules: [{
                max: 200,
                message: messages('common.max.characters.length', {max: 200}),
                required: true,
                whitespace: true
              }],
            })(
              <TextArea placeholder={messages('common.max.characters.length', {max: 200})} rows={3} style={{resize: 'none'}}/>
            )}
          </FormItem>
          <FormItem {...formItemLayout} label={paymentType === 'cash' ? messages('common.attachments')/*附件*/ : `${messages('loan-billing.key79')/*流水转账凭证*/}（${messages('common.max.image.length', {max: 3})}）`}>
            {getFieldDecorator('repayAttachment', {
              rules: [{
                required: paymentType === 'cash' ? false : !this.props.profile['ca.opt.didi.refund.upload.disabled'],
                message: messages('common.please.select')
              }],
              initialValue: []
            })(
              <ImageUpload attachmentType="REPAYMENT_IMAGES"
                           defaultFileList={repayAttachmentImages}
                           fileType={["PNG", 'png', 'JEPG', 'jepg', 'jpg', 'JPG', 'bmp', 'BMP',"jpg","JPG","jpeg","JPEG"]}
                           isShowDefault
                           maxNum={3}
                           onChange={this.getUploadImageOId}/>
            )}
          </FormItem>
          { paymentType === 'card' && (
            <div>
              <div className="title"> {messages('loan-billing.key80')/*收款方信息*/}
                <span>{messages('loan-billing.key81')/*请按以下收款方账号打款*/}</span>
              </div>
              <FormItem {...formItemLayout} label={messages('loan-billing.key186')/*开户公司*/} className="accept-account-container">
                {getFieldDecorator('acceptAccountName', {
                  rules: [{
                    required: true,
                    message: messages('common.please.select')
                  }],
                  initialValue: this.props.isOldCompany ? accountOptions[0] && accountOptions[0].id : info.companyOID
                })(
                  <Select placeholder={messages('common.please.select')}
                          showSearch
                          allowClear
                          disabled
                          filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                          getPopupContainer={() => document.getElementsByClassName('accept-account-container')[0]}
                          onChange={this.props.isOldCompany ? this.oldChangeAccount : this.newChangeAccount}
                          notFoundContent={selectLoading ? <Spin size="small" /> : messages('loan-billing.key82')/*无匹配结果*/}>
                    {accountOptions.map(option => {
                      return <Option key={option.id}>{option.companyName}</Option>
                    })}
                  </Select>
                )}
              </FormItem>
              {this.props.isOldCompany ? (
                // <FormItem {...formItemLayout} label={messages('loan-billing.key76')/*开户账号*/}>
                //   {getFieldDecorator('acceptAccount', {
                //     initialValue: acceptAccount
                //   })(
                //     <Input disabled/>
                //   )}
                // </FormItem>
                <FormItem {...formItemLayout} label={messages('loan-billing.key77')/*开户银行*/}>
                  {getFieldDecorator('acceptBankName', {
                    initialValue: acceptBankNumber
                  })(
                    <Input disabled/>
                  )}
                </FormItem>
              ) : (
                // <FormItem {...formItemLayout} label={messages('loan-billing.key76')/*开户账号*/} className="accept-account">
                //   {getFieldDecorator('acceptAccount', {
                //     rules: [{
                //       required: true,
                //       message: messages('common.please.select')
                //     }]
                //   })(
                //     <Select placeholder={messages('common.please.select')}
                //             showSearch
                //             allowClear
                //             onChange={this.handleChangeAcceptAccount}
                //             getPopupContainer={() => document.getElementsByClassName('accept-account')[0]}
                //             notFoundContent={bankSpin ? <Spin size="small"/> : messages('loan-billing.key82')/*无匹配结果*/}>
                //       {
                //         companyBankOption.map(option => {
                //           return <Option key={option.bankAccountNumber}>{option.bankAccountNumber}</Option>
                //         })
                //       }
                //     </Select>
                //   )}
                // </FormItem>
                <FormItem {...formItemLayout} label={messages('loan-billing.key77')/*开户银行*/} className="accept-account">
                  {getFieldDecorator('acceptBankName', {
                    rules: [{
                      required: true,
                      message: messages('common.please.select')
                    }]
                  })(
                    <Select placeholder={messages('common.please.select')}
                            showSearch
                            allowClear
                            onChange={this.handleChangeAcceptAccount}
                            getPopupContainer={() => document.getElementsByClassName('accept-account')[0]}
                            notFoundContent={bankSpin ? <Spin size="small"/> : messages('loan-billing.key82')/*无匹配结果*/}>
                      {
                        companyBankOption.map(option => {
                          return <Option key={option.bankAccountNumber}>{option.bankBranchName}</Option>
                        })
                      }
                    </Select>
                  )}
                </FormItem>
              )}
              <FormItem {...formItemLayout} label={messages('loan-billing.key76')/*开户帐号*/}>
                {getFieldDecorator('acceptAccount', {
                  initialValue: acceptAccount
                })(
                  <Input disabled/>
                )}
              </FormItem>
            </div>
          )}
        </Form>
        <div className="footer-operate" style={{backgroundColor:'#ffffff',left:'0px', marginRight: '10px' }}>
          <Button type="primary"  onClick={() => this.handleSave()} loading={loading}>
            {loanRefund ? messages('loan-billing.key83')/*确认*/ : messages('common.submit')/*提交*/}
          </Button>
          {showData && <Button onClick={() => this.handleSave(true)} loading={printLoading} style={{margin:'0px 10px'}}>
            {loanRefund ? messages('loan-billing.key155')/*确认并打印*/ : messages('loan-billing.key156')/*提交并打印*/}
          </Button>}
          <Button onClick={() => {this.props.close()}}>{messages('common.cancel')}</Button>
        </div>
      </div>
    )
  }
}

function mapStateToProps(state){
  return {
    profile: state.login.profile,
    isOldCompany: state.login.isOldCompany
  }
}

const WrappedEditLoan = Form.create()(RepaymentContent);

export default connect(mapStateToProps)(WrappedEditLoan);
